package day20;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * 将一个指定目录的java文件的绝对路径，存储到一个文本文件中
 * 即建立一个java文件的列表清单
 * 
 * @author wangbiao
 *
 */
public class JavaFilesList {

	public static void main(String[] args) {
		File dir = new File("D:\\MyProject\\javatest\\src");
		List<File> list = new ArrayList<File>(10*10);
		fileSaveToCollection(dir, list);
		File dest = new File(dir, "javalist.txt");
		writeToDestFile(list, dest );
	}
	
	//用一个集合来把所有的java文件存储起来
	public static void fileSaveToCollection(File dir, List<File> list) {
		File[] files = dir.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				fileSaveToCollection(file, list);
			} else {
				if (file.getName().endsWith(".java")) {
					list.add(file);
				}
			}
		}
	}
	
	//把文件的路径存入到目的文件中
	public static void writeToDestFile(List<File> list, File dest) {
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter(dest));
			for (File file : list) {
				bw.write(file.getAbsolutePath());
				bw.newLine();
				bw.flush();
			}
		} catch (IOException e) {
			throw new RuntimeException("写入文件失败！");
		} finally {
			if (null != bw) {
				try {
					bw.close();
				} catch (IOException e) {
					throw new RuntimeException("写入缓冲流关闭失败！");
				}
			}
		}
	}
}
